package models

import (
	"fmt"
	"github.com/beego/beego/v2/client/orm"
	"github.com/beego/beego/v2/server/web"
	_ "github.com/go-sql-driver/mysql"
	"rate/pojo/entity"
	"time"
)

var Orm orm.Ormer

func init() {
	// 数据库连接
	dsn := ""
	if web.BConfig.RunMode == "dev" {
		dsn = fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&loc=PRC&parseTime=true",
			web.AppConfig.DefaultString("dev::MysqlUser", "root"),
			web.AppConfig.DefaultString("dev::MysqlPass", "root"),
			web.AppConfig.DefaultString("dev::MysqlUrls", "127.0.0.1"),
			web.AppConfig.DefaultInt("dev::MysqlPort", 3306),
			web.AppConfig.DefaultString("dev::Mysqldb", "rate"),
		)
	} else {
		dsn = fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&loc=PRC&parseTime=true",
			web.AppConfig.DefaultString("pro::MysqlUser", "root"),
			web.AppConfig.DefaultString("pro::MysqlPass", "root"),
			web.AppConfig.DefaultString("pro::MysqlUrls", "127.0.0.1"),
			web.AppConfig.DefaultInt("pro::MysqlPort", 3306),
			web.AppConfig.DefaultString("pro::Mysqldb", "rate"),
		)
	}

	_ = orm.RegisterDriver("mysql", orm.DRMySQL)
	_ = orm.RegisterDataBase("default", "mysql", dsn)
	orm.RegisterModel(&entity.Member{}, &entity.EmailRecord{})
	orm.RunCommand()
	orm.DefaultTimeLoc = time.UTC
	_ = orm.RunSyncdb("default", false, true)
	if web.BConfig.RunMode == "dev" {
		orm.Debug = true
	}
	// orm 创建
	Orm = orm.NewOrm()
}
